<?php
namespace app\admin\model;

class AdminUser extends \app\common\model\Base
{
	protected $table = 'admin_user';
	protected $createTime = 'create_time';
	protected $updateTime = false;
	protected $autoWriteTimestamp = true;
	protected $insert = [
		'status' => 1,
	];

	protected $append=['group_ids'];

	use \app\common\model\TreeBase;

	protected $_RejectCreate = ['user_name','password','create_time','pid','status','last_login'];
	protected $_RejectUpdate = ['user_name','password','create_time','pid','status','last_login'];

	protected function _before_updateDataById(&$param) {
		if ($GLOBALS['userInfo']['uid']!=$param['id']){
			unset($param['email']);
			unset($param['real_name']);
		}
		return true;
	}

	protected function _after_createData(&$param){
		if (isset($param['group_ids'])) {
			$u = $this->get($param['id']);
			if (!$u->setGroups($param['group_ids'])) {
				return $u->getError();
			}
		}
		return true;
	}

	protected function _after_updateDataById(&$param){
		if (isset($param['group_ids'])) {
			$u = $this->get($param['id']);
			if (!$u->setGroups($param['group_ids'])) {
				return $u->getError();
			}
		}
		return true;
	}

	public function getGroupIdsAttr() {
		return $this->groups()->column('id');
	}

	public function groups() {
		return $this->belongsToMany('Group', 'admin_access', 'group_id', 'user_id');
	}

	public function setGroups($gids) {
		$groupModel = new Group;
		if (!in_array(0, $GLOBALS['userInfo']['gids'])) {
			$allChildren = $groupModel->getAllChild($GLOBALS['userInfo']['gids']);
			if (!count(array_diff($gids, $allChildren))) {
				$this->error = "不能赋予他人比自己更高的等级的用户组";
				return false;
			}
		}
		$id=$this->getAttr('id');
		$db=db('admin_access');
		$db->where('user_id',$id)->delete();

		if (count($gids)) {
			foreach ($gids as &$v) {
				$v = ['group_id'=>$v,'user_id'=>$id];
			}
			$db->data($gids)->insertAll();
		}
		return true;
	}

  /**
   * reload the user cache according to $authKey(this function exists why we should make APIs stateless)
   *
   * @param string $authKey
   *
   * @return boolean
   */
	public function createUserCache($authKey, $userInfo=null){
		if (strlen($authKey)<=32)
			return false;
		$md5=substr($authKey,0,32);
		$id=substr($authKey,32);
		if (!$userInfo)
			$userInfo=$this->where('status',1)->get($id);
		if ($userInfo){
			if ($md5==user_md5($userInfo['user_name'].$userInfo['password'].$userInfo['last_login'])){
				//when password right
				$gids=Group::getGroupsList($userInfo['id']);
				$gidskeys=implode('_',$gids);
				$info['UserInfo'] = [
					'uid'=>$userInfo['id'],
					'gids'=>$gids,
					'gidkeys'=>$gidskeys,
					'site_id'=>$userInfo['site_id'],
				];
				cache('Auth_'.$authKey, $info, config('LOGIN_SESSION_VALID'),'AUTH');
				return true;
			}
		}
		return false;
	}

  /**
   * login interface
   *
   * @param string $username
   * @param string $password
   * @param boolean $isRemember
   *
   * @return Array|null if login successfully,retrun the login data.otherwise,return null,
   */
	public function login($username, $password, $isRemember = false) {
		if (!$username) {
			$this->error = '帐号不能为空';
			return null;
		}
		if (!$password){
			$this->error = '密码不能为空';
			return null;
		}

		$map['user_name'] = $username;
		$userInfo = $this->where($map)->find();
		if (!$userInfo) {
			$this->error = '帐号不存在';
			return null;
		}
		if (user_md5($password) !== $userInfo['password']) {
			$this->error = '密码错误';
			return null;
		}
		if ($userInfo['status'] === 0) {
			$this->error = '帐号已被禁用';
			return null;
		}

		if ($isRemember) {
			$secret['user_name'] = $username;
			$secret['password'] = $password;
			$data['rememberKey'] = encrypt($secret);
		}

		$authKey = user_md5($userInfo['user_name'].$userInfo['password'].$userInfo['last_login']).$userInfo['id'];
		cache('Auth_'.$authKey, null);

		$userInfo['last_login']=time();
		$userInfo->isUpdate(true)->save();

		$authKey = user_md5($userInfo['user_name'].$userInfo['password'].$userInfo['last_login']).$userInfo['id'];

		if (!$this->createUserCache($authKey,$userInfo)){
			$this->error = '建立用户缓存失败';
			return null;
		}

		$data['authKey']	= $authKey;
		$data['userInfo']	= $userInfo->visible(['user_name','email','real_name']);
		return $data;
	}

	/**
	 * 修改密码(should be refactored)
	 * @param  array   $param  [description]
	 */
	public function setInfo($auth_key, $old_pwd, $new_pwd)
	{
		$cache = cache('Auth_'.$auth_key);
		if (!$cache) {
			$this->error = '请先进行登录';
			return false;
		}
		if (!$old_pwd) {
			$this->error = '请输入旧密码';
			return false;
		}
		if (!$new_pwd) {
			$this->error = '请输入新密码';
			return false;
		}
		if ($new_pwd == $old_pwd) {
			$this->error = '新旧密码不能一致';
			return false;
		}

		$userInfo = $cache['userInfo'];
		$password = $this->where('id', $userInfo['id'])->value('password');
		if (user_md5($old_pwd) != $password) {
			$this->error = '原密码错误';
			return false;
		}
		$new_pwd= user_md5($new_pwd);
		if ($new_pwd == $password) {
			$this->error = '密码没改变';
			return false;
		}

		if ($this->where('id', $userInfo['id'])->setField('password', $new_pwd)) {
			return $this->login($userInfo['user_name'],$new_pwd);
		}

		$this->error = '修改失败';
		return false;
	}
}
